package com.recipedb.recipedb.service.impl;

import com.recipedb.recipedb.entity.Step;
import com.recipedb.recipedb.repository.StepRepository;
import com.recipedb.recipedb.service.StepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class StepServiceImpl implements StepService {

    @Autowired
    private StepRepository repository;

    @Override
    public Step save(Step entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(Long id) {
        repository.deleteById(id);
    }

    @Override
    public Optional<Step> findById(Long id) {
        return repository.findById(id);
    }

    @Override
    public List<Step> findAll() {
        return repository.findAll();
    }

    @Override
    @Transactional
    public Optional<Step> partialUpdate(Long id, Step entity) {
        return repository.findById(id)
                .map(existingStep -> {

                    if (entity.getStepOrder() != null) {
                        existingStep.setStepOrder(entity.getStepOrder());
                    }
                    if (entity.getDescription() != null) {
                        existingStep.setDescription(entity.getDescription());
                    }
                    if (entity.getMethod() != null) {
                        existingStep.setMethod(entity.getMethod());
                    }
                    if (entity.getRecommendedDuration() != null) {
                        existingStep.setRecommendedDuration(entity.getRecommendedDuration());
                    }
                    if (entity.getAvgDuration() != null) {
                        existingStep.setAvgDuration(entity.getAvgDuration());
                    }
                    if (entity.getMinDuration() != null) {
                        existingStep.setMinDuration(entity.getMinDuration());
                    }
                    if (entity.getMaxDuration() != null) {
                        existingStep.setMaxDuration(entity.getMaxDuration());
                    }
                    // imagePath 不在 partialUpdate 里自动更新，保持你原逻辑的独立性

                    return repository.save(existingStep);
                });
    }

    @Override
    public List<Step> findByRecipeId(Long recipeId) {
        return repository.findByRecipeId(recipeId);
    }

    @Override
    @Transactional
    public void updateImagePath(Long id, String imagePath) {
        repository.updateImagePath(id, imagePath);
    }

    @Override
    @Transactional
    public void clearImagePath(Long id) {
        repository.clearImagePath(id);
    }
}
